$(function () {
  // 对Date的扩展，将 Date 转化为指定格式的String
  // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
  // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  // 例子：
  // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
  Date.prototype.Format = function (fmt) {
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
        ((
          "00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }

  var time = new Date();
  var nowTime = time.Format('yyyy-MM-dd hh:mm');
  var nowYear = time.getFullYear();
  var nowMonth = time.getMonth();
  var choosableMonths = [];
  var minTime = time.Format('yyyy-MM-dd');
  for (var i = nowMonth; i <= 12; i++) {
    choosableMonths.push(i);
  }
  $("#datetime-picker").val(nowTime);
  $("#datetime-picker").datetimePicker({
    title: '截止日期',
    // 截止时间只能选择未来的时间
    min: minTime,
    // years: [nowYear],
    // monthes: choosableMonths
  });

  // 添加选项，改用最高父级委托
  // $('.add-select-item').delegate(this, 'click', function () {
  //   var selectTmp = '<div class="weui-cell">' +
  //     '<div class="weui-cell__hd">' +
  //     '</div>' +
  //     '<div class="weui-cell__bd">' +
  //     '<i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">' +
  //     '</div>' +
  //     '</div>';
  //   var selectItem = $('.select-group-item .weui-cell').clone()[0] || selectTmp;
  //   $(selectItem).find('input').val('').attr('placeholder', '选项');
  //   $('.select-group-item').append(selectItem);
  // });

  // 删除选项，改用最高父级委托
  // $('.select-group-item').delegate('.weui-icon-delete, .weui-icon-reduce', 'click', function (evt) {
  //   console.log(evt);
  //   $(evt.currentTarget.parentNode.parentNode).remove();
  // })

  // 添加题目
  $('#add-topic').click(function () {
    var topicTmp = '<div class="topic-wrapper">' +
      '<div class="weui-cell weui-cell_access flex-justify-space-between">' +
      '<div class="weui-cell___bd">' +
      '<input class="weui-input select-item" type="tel" placeholder="投票标题(必填)">' +
      '</div>' +
      '<div class="weui-cell__ft checkbox-box">' +
      '<input type="text" class="checkbox-s" placeholder="1"/>' +
      '</div>' +
      '</div>' +
      '<div class="select-group-item">' +
      '<div class="weui-cell">' +
      '<div class="weui-cell__hd">' +
      '</div>' +
      '<div class="weui-cell__bd">' +
      '<i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">' +
      '</div>' +
      '</div>' +
      '<div class="weui-cell">' +
      '<div class="weui-cell__hd">' +
      '</div>' +
      '<div class="weui-cell__bd">' +
      '<i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">' +
      '</div>' +
      '</div>' +
      '</div>' +
      '<a href="javascript:void(0);" class="weui-cell weui-cell_link">' +
      '<div class="weui-cell__bd add-select-item"> <i class="weui-icon-addition"></i>' +
      '<p class="p_add-select-item">添加选项</p>' +
      '</div>' +
      '</a>' +
      '<div class="weui-cells__title delete-topic"><span class="close">+</span>删除本题</div>' +
      '</div>';

    $('.vote-box').append(topicTmp);
  })

  $('.vote-box').on('click', '.delete-topic', function (evt) {
    if (evt.currentTarget.parentNode && evt.currentTarget.parentNode.parentNode.children.length > 1) {
      console.log(evt.currentTarget.parentNode.parentNode.children.length)
      $(evt.currentTarget.parentNode).remove();
    }
  })

  var itemSelectArray;
  // 添加选项
  $('.vote-box').on('click', '.add-select-item', function (evt) {
    var selectTmp = '<div class="weui-cell">' +
      '<div class="weui-cell__hd">' +
      '</div>' +
      '<div class="weui-cell__bd">' +
      '<i class="weui-icon-reduce"></i><input class="weui-input select-item" type="text" placeholder="选项">' +
      '</div>' +
      '</div>';
    var selectItem = $('.select-group-item .weui-cell').clone()[0] || selectTmp;
    $(selectItem).find('input').val('').attr('placeholder', '选项');
    $(evt.currentTarget.parentNode.parentNode.children[1]).append(selectItem);
    console.log($(this).parent().parent().find('.checkbox-box'));
    // fixed 自动触发一次点击事件，解决需要点击两次的bug
    $($(this).parent().parent().find('.checkbox-box')).trigger('click');
  })

  // 删除选项
  $('.vote-box').on('click', '.weui-icon-delete, .weui-icon-reduce', function (evt) {
    if (evt.currentTarget.parentNode.parentNode.parentNode.childElementCount > 2) {
      $(evt.currentTarget.parentNode.parentNode).remove();
    }
  })

  $('#submit').click(function () {
    var postData = [];
    var selectItem = $('.select-item');
    // [].map.call($('.select-item'), function (i) {
    //   console.log(i)
    // })

    $.map($('.vote-box .topic-wrapper'), function (topic, topicIndex) {
      // console.log(topic)
      var tmp = [];
      var itemData = [];
      $.map($(topic).find('.select-item'), function (item, itemIndex) {
        // console.log(itemIndex);
        var a = $($(item).find('.select-item')[itemIndex]);
        // console.log(a.val());
        itemData.push({
          "id": itemIndex,
          "name": $(item).val(),
          "value": itemIndex
        })
      })
      postData.push({
        "id": topicIndex,
        "name": $(topic).find('input').eq(0).val(),
        "value": topicIndex,
        "data": itemData
      })

      $('#datetime-picker').val();
    })

    var data = {
      "expiration": $('#datetime-picker').val(),
      "isAnonymous": $('#isAnonymous').is(':checked'),
      "vote": postData
    }

    console.log(data);
    $.ajax({
      type: "POST",
      url: "__CONTROLLER__/saveListDataIndex",
      data: data,
      dataType: "html",
      success: function (response) {
        console.log(response);
      }
    });
  })

  /** 
   * * 控制单选多选
  */
  $('.vote-box').on('click', '.checkbox-box', function (evt) {
    var $this = $(this);
    // 获取选项数
    var selectGroupItem = $(this).parents('.topic-wrapper').children('.select-group-item');
    var itemNum = selectGroupItem.find('.select-item').length;
    itemSelectArray = Array.from({
      length: itemNum
    }).map((v, k) => k + 1)
    console.log('TCL: itemSelectArray', itemSelectArray);

    // var checkboxHtml = '<input type="text" class="checkbox-s" />';
    // $(this).empty();
    // $(this).html(checkboxHtml);

    $($(this).children()).picker({
      title: '设置可选数',
      cols: [{
        textAlign: 'center',
        values: itemSelectArray ? itemSelectArray : [1, 2]
      }],
      defaultValue: [1],
      onClose: function(picker) {
        console.log(picker)
        console.log($($this).children().val())
      }
    })

    /**
     * * ref https://github.com/lihongxun945/jquery-weui/issues/341
     * ! fixed 
     */
    if ($($(this).children()).data('picker').cols[0]) {
      $($(this).children()).data('picker').cols[0].values = itemSelectArray ? itemSelectArray : [1, 2];
    }
    // picker.picker({
    //   textAlign: 'center',
    //   values: itemSelectArray ? itemSelectArray : [1, 2]
    // })


    // $($(this).children()).select({
    //   title: "设置可选择的选项数",
    //   items: itemSelectArray ? itemSelectArray : ['1', '2'],
    //   opOpen: function (select) {
    //     console.log(select)
    //   },
    //   onChange: function (select) {
    //     console.log('TCL: select', select);
    //   },
    //   opClose: function (select) {
    //     console.log('TCL: select', select);
    //   }
    // });
    // $($(this).children()).val('').data('weui-select', false).select({
    //   title: "设置可选择的选项数",
    //   items: itemSelectArray ? itemSelectArray : ['1', '2'],
    // });

  });

  // 控制单选多选
  // $('.vote-box').on('click', '.checkbox-s', function (evt) {
  //   // 获取选项数
  //   var checkboxHtml = '<input type="text" class="checkbox-s" />';
  //   var parentBox = $(this).parent();
  //   parentBox.empty();
  //   parentBox.append(checkboxHtml);
  // })
  
  // 加载完成自动触发一次
  $('.checkbox-box').trigger('click');
})